import time

import requests
from app.utils.decorator import cache_func_data
from app.config import GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, GITHUB_USER_URL, GITHUB_TOKEN_URL
from flask import abort
from app.models import User


@cache_func_data(cache_time=600)
def get_github_user(code):
    payload = {
        'client_id': GITHUB_CLIENT_ID,
        'client_secret': GITHUB_CLIENT_SECRET,
        'code': code
    }
    response = requests.post(
        GITHUB_TOKEN_URL,
        headers={'Accept': 'application/json'},
        data=payload
    )
    token_info = response.json()

    if token_info.get("error_description"):
        abort(400, token_info["error_description"])

    headers = {'Authorization': 'token {}'.format(token_info["access_token"])}
    user_info = requests.get(GITHUB_USER_URL, headers=headers).json()
    return user_info, token_info


@cache_func_data(cache_time=3600 * 24 * 7)
def get_all_start_by_page(page):
    url = "https://api.github.com/repos/dairoot/ChatGPT-Mirror/stargazers"
    user = User.query.order_by(User.update_time.desc()).first()
    headers = {'Authorization': 'token {}'.format(user.user_token)}
    res = requests.get(url, params={"page": page}, headers=headers)
    return [i["id"] for i in res.json()]


def get_all_start():
    page = 0
    all_user_id_list = []
    while True:
        page += 1
        user_id_list = get_all_start_by_page(page)
        all_user_id_list += user_id_list

        if not user_id_list:
            all_user_id_list += get_all_start_by_page(page - 1, forced_refresh=True)
            break
        # time.sleep(1)

    return set(all_user_id_list)
